﻿<%@ WebHandler Language="C#" Class="WorkcenterCooperation" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 工区协作查询报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.4.20
 **/

public class WorkcenterCooperation : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT cci.mfgordername,cci.productname,cci.containername,w.workcentername applyWorkcenter,ws.workflowstepname,e.fullname,c.originalqty,
       w2.workcentername toWorkcener,cwd.createdate,e2.fullname receiver,cwd.recvdate,cwd.estimatedsenddate,cwd.completedate,csd.checkdate,
       CASE WHEN cwd.completedate IS NULL THEN 0
            WHEN cwd.completedate IS NOT NULL AND csd.checkdate IS NULL THEN TRUNC(SYSDATE) - cwd.completedate
            WHEN cwd.completedate IS NOT NULL AND csd.checkdate IS NOT NULL THEN TRUNC(csd.checkdate) - cwd.completedate
       END delayhours,
       cci.workflowstepname currentworkflowstepname,wfb.workflowname,wf.workflowrevision
FROM containerworkcenterdispatch cwd
INNER JOIN containercurrentinfo cci ON cci.containerid = cwd.containerid
LEFT JOIN container c ON c.containerid = cwd.containerid
LEFT JOIN workcenter w ON w.workcenterid = cwd.workcenterid
LEFT JOIN workcenter w2 ON w2.workcenterid = cwd.toworkcenterid
LEFT JOIN workflowstep ws ON ws.workflowstepid = cwd.workflowstepid
LEFT JOIN containersteprecord csd ON csd.containerid = cwd.containerid AND csd.workflowstepid = cwd.workflowstepid
LEFT JOIN employee e ON e.employeeid = cwd.employeeid
LEFT JOIN employee e2 ON cwd.RecvEmployeeID = e2.employeeid
LEFT JOIN workflow wf ON wf.workflowid = ws.workflowid
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = wf.workflowbaseid
WHERE cwd.isuse = 0 AND cci.containerstatus = 1 
";
        //分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //申请工区
        if (jObject["fromworkcenterid"] != null && jObject["fromworkcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cwd.workcenterid = '{0}'", jObject["fromworkcenterid"].ToString());
        }

        //协作工区
        if (jObject["toworkcenterid"] != null && jObject["toworkcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cwd.toworkcenterid = '{0}'", jObject["toworkcenterid"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //申请时间
        if (jObject["createdate"] != null && jObject["createdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["createdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(cwd.createdate) BETWEEN TO_DATE('{0}','yyyy-mm-dd') and TO_DATE('{1}','yyyy-mm-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }

        //状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            if (jObject["status"].ToString() == "已超期")
            {
                sql += " AND ((csd.checkdate IS NULL AND SYSDATE > cwd.completedate )OR(csd.checkdate IS NOT NULL AND csd.checkdate>cwd.completedate)) ";
            }
            else
            {
                sql += " AND ((csd.checkdate IS NULL AND SYSDATE < cwd.completedate )OR(csd.checkdate IS NOT NULL AND csd.checkdate<cwd.completedate) OR (cwd.completedate IS NULL))  ";
            }
        }

        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        Result r = new Result();
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["productname"].Caption = "零件图号";
        dtResult.Columns["containername"].Caption = "流水卡号";
        dtResult.Columns["applyworkcenter"].Caption = "申请工区";
        dtResult.Columns["workflowstepname"].Caption = "申请工序";
        dtResult.Columns["fullname"].Caption = "申请人";
        dtResult.Columns["originalqty"].Caption = "计划数";
        dtResult.Columns["toworkcener"].Caption = "协作工区";
        dtResult.Columns["createdate"].Caption = "申请时间";
        dtResult.Columns["receiver"].Caption = "接收人";
        dtResult.Columns["recvdate"].Caption = "接收时间";
        dtResult.Columns["estimatedsenddate"].Caption = "预计发出时间";
        dtResult.Columns["completedate"].Caption = "要求完成时间";
        dtResult.Columns["checkdate"].Caption = "实际完成时间";
        dtResult.Columns["delayhours"].Caption = "超期天数";
        dtResult.Columns["currentworkflowstepname"].Caption = "当前工序";
        dtResult.Columns["workflowname"].Caption = "工艺路线";
        dtResult.Columns["workflowrevision"].Caption = "工艺版本";
        ExportHelper.ExportExcel(dtResult, "工序协作查询报表");
    }
}